import axios from 'axios'
import { Message } from 'element-ui'
import { throttle } from 'lodash'
import cookies from 'js-cookie'
// import qs from 'qs'

const errorHandler = throttle(function (result = {}) {
  const { message } = result
  Message.error({
    content: message
  })
  // 白名单 不处理
}, 2000)

const err = error => {
  if (error.response) {
    const data = error.response.data
    if (error.response.status === 403) {
      errorHandler({
        message: 'Forbidden',
        description: data.message
      })
    }
    if (error.response.status === 404) {
      errorHandler({
        message: 'Not Found',
        description: data.message
      })
    }
    if (error.response.status === 401) {
      errorHandler({
        message: '登录超时',
        description: 'Authorization verification failed'
      })
    }
  }
  return Promise.reject(error)
}

function initInstance (options) {
  // 创建 axios 实例
  const service = axios.create({
    timeout: 60000, // 请求超时时间
    headers: {
      // 'Content-Type': 'application/json'
      // 'Content-Type': 'application/x-www-form-urlencoded'
      // 'X-ZT-Token': store.state.token
    },
    // withCredentials: true,
    responseType: 'json',
    ...options
  })

  // request interceptor
  service.interceptors.request.use(config => {
    const sIdCookie = cookies.get('sessionId')
    config.headers.Authorization = sIdCookie
    return config
  }, err)

  // response interceptor
  service.interceptors.response.use(response => {
    console.log('response', response)
    const { code, msg } = response.data
    const isSuccess = code === options.successCode
    if (code === 500 && msg === 'token is error') {
      errorHandler({
        message: '登录超时',
        description: 'Authorization verification failed'
      })
    }
    return { ...response.data, isSuccess }
  }, err)
  return service
}

const service = initInstance({
  baseURL: window.API_BASE, // api base_url
  successCode: 200
})

export default service
